package com.hkts.naturalgas.config;


import com.alibaba.fastjson.JSONObject;
import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import lombok.extern.apachecommons.CommonsLog;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
@CommonsLog
@Component
public class TokenFilter implements GlobalFilter, Ordered {
   //限流配置
    @Autowired
    private IpLimit ipLimit;

    private static final Map<String,Bucket> CACHE = new ConcurrentHashMap<>();
    private Bucket createNewBucket() {
        Refill refill = Refill.of(ipLimit.getRefillTokens(),Duration.ofSeconds(ipLimit.getSeconds()));
        Bandwidth limit = Bandwidth.classic(ipLimit.getCapacity(),refill);
        return Bucket4j.builder().addLimit(limit).build();
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /*String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
        Bucket bucket = CACHE.computeIfAbsent(ip,k -> createNewBucket());

        log.debug("IP: " + ip + "，TokenBucket Available Tokens: " + bucket.getAvailableTokens());
        if (bucket.tryConsume(1)) {
            return chain.filter(exchange);
        } else {
            ServerHttpResponse response = exchange.getResponse();
            JSONObject message = new JSONObject();
            message.put("message", "error");
            message.put("code", 500);
            message.put("timestamp", System.currentTimeMillis());
            message.put("result", "请您点击速度慢一点！");
            byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }*/
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1000;
    }
}
